﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Faust.Andrew.MTG
{
    public class CachedGatherer : Gatherer
    {
        private DataStore _dataStore;
        Gatherer _gatherer;      

        public CachedGatherer(DataStore dataStore)
        {
            if (dataStore == null)
            {
                throw new ArgumentNullException("dataStore", "dataStore is null.");
            }

            _dataStore = dataStore;
            _gatherer = new WebGatherer();   
        }

        public override CardSearchResults FindCards(CardSearchParameters searchParameters)
        {
            return FindCards(searchParameters, true);
        }

        public override CardSearchResults FindCards(CardSearchParameters searchParameters, bool loadDetails)
        {
            //We don't want to initially get the card details as we'll try to get them from the data
            //store first.            
            CardSearchResults results = null;

            if (searchParameters.Owned || !searchParameters.UseGatherer || !String.IsNullOrEmpty(searchParameters.CustomWhereClause))
            {
                //If we only want to search for cards that are owned by the user then we only need to check the
                //local database
                results = _dataStore.FindCards(searchParameters);
            }
            else
            {
                results = _gatherer.FindCards(searchParameters, false);
            }

            //If the caller want's the details we'll now load them while first checking the local data store
            if (loadDetails)
            {
                LoadCardDetails(results.Cards);
            }

            return results;
        }

        public override void LoadCardDetails(List<Card> cards)
        {
            cards.ForEach(card => LoadCardDetails(card));
        }

        public override void LoadCardDetails(Card card)
        {
            Card dataStoreCard = _dataStore.FindCard(card.MultiverseID);

            if (dataStoreCard != null)
            {
                card.CopyFrom(dataStoreCard);
            }
            else
            {
                _gatherer.LoadCardDetails(card);
                _dataStore.AddCard(card, false);
            }
        }

        public override Gatherer Clone()
        {
            return new CachedGatherer(_dataStore);
        }
    }
}
